﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LOGISTCBUS.Entities;
using LOGISTCBUS.DAO;

namespace LOGISTCBUS.WebUI.Controllers
{
    public class ConfigurationController : Controller
    {
        public ActionResult Index()
        {
            var user = (User)this.Session["user"];
            if (user == null)
                return RedirectToAction(@"LogOut", @"Account");
            return View();
        }

        public ActionResult Edit()
        {
            var userLogged = (User)this.Session["user"];
            if (userLogged == null)
                return RedirectToAction(@"LogOut", @"Account");

            var lst = new ConfigurationDAO().select();
            var configuration = new LOGISTCBUS.Entities.Configuration();
            if (lst != null && lst.Count > 0)
                configuration = lst.FirstOrDefault();
            this.ViewData[@"configuration"] = configuration == null ? new LOGISTCBUS.Entities.Configuration() : configuration;

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Save(int id)
        {
            var c = id > 0 ? new ConfigurationDAO().selectById(id) : new LOGISTCBUS.Entities.Configuration();
            var aux = true;

            c.Email = !String.IsNullOrEmpty(Request.Params["email"]) ? Request.Params["email"] : null;
            if (!String.IsNullOrEmpty(Request.Params["password"]))
                c.Password = Request.Params["password"];
            c.Host = !String.IsNullOrEmpty(Request.Params["host"]) ? Request.Params["host"] : null;
            c.Port = !String.IsNullOrEmpty(Request.Params["port"]) ? Convert.ToInt32(Request.Params["port"]) : new Nullable<Int32>();

            if (c.Id > 0)
                aux = new ConfigurationDAO().update(c);
            else
                aux = new ConfigurationDAO().insert(c);

            var obj = new
            {
                success = aux,
                message = "Configuração salva com sucesso!"
            };

            return Json(obj);
        }
    }
}
